package com.gitee.huanminabc.utils_tools.spring_base.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;

@Slf4j
public class SpringAopProxyUtil {
    //判断如果是代理对象那么取出来原始对象

    public static Class getTargetClass(Object proxy) {
        if (!org.springframework.aop.support.AopUtils.isAopProxy(proxy)) {
            return AopUtils.getTargetClass(proxy);//不是代理对象
        }
        if (org.springframework.aop.support.AopUtils.isCglibProxy(proxy)) {
            return AopUtils.getTargetClass(proxy);
        }
        return proxy.getClass();
    }
    //修改代理对象的目标对象
    public static Object getTarget(Object proxy) {
        if (!org.springframework.aop.support.AopUtils.isAopProxy(proxy)) {
            return proxy;
        }
        try {
            if (org.springframework.aop.support.AopUtils.isJdkDynamicProxy(proxy)) {
                return getJdkDynamicProxyTargetObject(proxy);
            } else { //cglib
                return getCglibProxyTargetObject(proxy);
            }
        } catch (Exception e) {
            log.error("获取目标对象失败", e);
        }
        return null;
    }
    //jdk动态代理
    private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
        java.lang.reflect.Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        org.springframework.aop.framework.AdvisedSupport advised = (org.springframework.aop.framework.AdvisedSupport) h.get(proxy);
        Object target = advised.getTargetSource().getTarget();
        return target;
    }
    //cglib代理
    private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
        java.lang.reflect.Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);
        Object dynamicAdvisedInterceptor = h.get(proxy);
        java.lang.reflect.Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        org.springframework.aop.framework.AdvisedSupport advised1 = (org.springframework.aop.framework.AdvisedSupport) advised.get(dynamicAdvisedInterceptor);
        Object target = advised1.getTargetSource().getTarget();
        return target;
    }

}
